﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using System.Runtime.InteropServices;
using System.Windows;
using UDITool;

namespace ZebraUDI
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool AllocConsole();

        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool FreeConsole();

        public static Action<UDICode> UDIEvent;


        protected override void OnStartup(StartupEventArgs e)
        {
            //AllocConsole();

            Task.Run(() =>
            {
                var builder = WebApplication.CreateBuilder(e.Args);

                builder.Services.AddControllers();

                var app = builder.Build();

                app.MapPost("/udi", (UDICode data) =>
                {
                    UDIEvent?.Invoke(data);
                    return Results.Ok(new { Message = "Data received", ReceivedData = data });
                });
                string host = "0.0.0.0";
                int port = 5110;
                app.Run($"http://{host}:{port}");
            });

            base.OnStartup(e);
        }
    }


}
